#define DDCLLUA_CORE

#include "ddcllog.h"
#include "lua-ddcl.h"
#include "lua-ddclservice.h"

static int
l_log (lua_State * L){
    ddcl_Service from = 0;
    //lua_pushstring(L, LDDCL_CTX_K);
    lua_rawgetp(L, LUA_REGISTRYINDEX, &LDDCL_CTX_K);
    if(!lua_isnil(L, -1)){
        Context * ctx = lua_touserdata(L, -1);
        from = ctx->svr;
    }
    lua_pop(L, 1);

    int top = lua_gettop(L);
    if(!top){
        return 0;
    }
    lua_newtable(L);
    for (int i = 1; i <= top; i ++){
        lua_getglobal(L, "tostring");
        lua_pushvalue(L, i);
        lua_call(L, 1, 1);
        lua_rawseti(L, -2, i);
    }
    lua_getglobal(L, "table");
    lua_pushstring(L, "concat");
    lua_rawget(L, -2);
    lua_pushvalue(L, -3);
    lua_pushstring(L, "  ");
    lua_call(L, 2, 1);
    const char * str = lua_tostring(L, -1);
    ddcl_log(from, str);
    lua_pop(L, 3);
    return 0;
}

static int
l_set (lua_State * L){
    ddcl_Service svr = luaL_checkinteger(L, 1);
    ddcl_set_log_service(svr);
    return 0;
}

static luaL_Reg _REG[] = {
    { NULL, NULL},
};

DDCLLUA int
luaopen_ddcl_log (lua_State * L){
    luaL_checkversion(L);
    DDLUA_NEWLIB(L, "ddcl.log", _REG);
    luapush_ddcl_log(L, -1);
    return 1;
}


DDCLLUA int
luapush_ddcl_log (lua_State * L, int i){
    lua_checkstack(L, 3);
    lua_pushvalue(L, i);
    DDLUA_PUSHFUNC(L, "log", l_log);
    DDLUA_PUSHFUNC(L, "set", l_set);
    lua_pop(L, 1);
    return 0;
}
